package com.example.javamaday.offer;

import com.example.javamaday.leetcode.base.TreeNode;

import java.util.Stack;

public class GetOffer55 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left= new TreeNode(15);
        root.right.right = new TreeNode(7);
        int i = new GetOffer55().maxDepth(root);
        System.out.println(i);
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> treeNodeStack = new Stack<>();
        Stack<TreeNode> helpStack = new Stack<>();
        int depth = 1;
        boolean isRevert = false;
        treeNodeStack.push(root);
        while (true) {
            if (!isRevert) {
                if (!treeNodeStack.isEmpty()) {
                    TreeNode node = treeNodeStack.pop();
                    if (node.left != null) {
                        helpStack.push(node.left);
                    }
                    if (node.right != null) {
                        helpStack.push(node.right);
                    }
                } else {
                    if (helpStack.isEmpty()) {
                        break;
                    } else {
                        depth++;
                        isRevert = true;
                    }
                }
            } else {
                if (!helpStack.isEmpty()) {
                    TreeNode node = helpStack.pop();
                    if (node.left != null) {
                        treeNodeStack.push(node.left);
                    }
                    if (node.right != null) {
                        treeNodeStack.push(node.right);
                    }
                } else {
                    if (treeNodeStack.isEmpty()) {
                        break;
                    } else {
                        depth++;
                        isRevert = false;
                    }
                }
            }
        }
        return depth;
    }
}
